package biolabs.space;

/**
 * Extends the {@link GenericGrid} with more efficient 2D operations.
 *
 * @author Tomas Mikula
 */
public class Generic2DGrid<T> extends GenericGrid<T, Discrete2DPosition, Continuous2DPosition> {

	public Generic2DGrid(Discrete2DPosition size) {
		super(size);
	}

	public T at(int x, int y){
		if(!inRange(x, y))
			throw new ArrayIndexOutOfBoundsException(new Discrete2DPosition(x, y) + " is out of " + size);
		return array[computeIndex(x, y)];
	}

	public T setField(int x, int y, T value){
		if(!inRange(x, y))
			throw new ArrayIndexOutOfBoundsException(new Discrete2DPosition(x, y) + " is out of " + getSize());
		int i = computeIndex(x, y);
		T res = array[i];
		array[i] = value;
		return res;
	}

	private boolean inRange(int x, int y) {
		if(x<0 || x>=size.x)
			return false;
		if(y<0 || y>=size.y)
			return false;
		return true;
	}

	private int computeIndex(int x, int y) {
		return x*size.y + y;
	}
}
